/** @format */

import { resultsModel } from '../../../sdk'
import { CODE_TYPES } from '../../../errorCode'
import { dbFindOne } from '../mongodb'
import { JOIN_DB_NAME } from '../../../db'

export default async function checkJoinId(context: IContext<IParams>) {
  const { openId } = context
  const { gameId, activityId } = context.data
  if (!gameId) {
    return resultsModel.error(CODE_TYPES.PARAMS_ERROR, `缺少gameId参数`)
  }
  const joinInfo = await dbFindOne<IJoinRecord>(context, JOIN_DB_NAME, { _id: gameId, activityId })

  if (joinInfo?.submitTime) return resultsModel.error(CODE_TYPES.PARAMS_ERROR, `重复提交游戏！`)

  if (joinInfo?.openId !== openId) return resultsModel.error(CODE_TYPES.PARAMS_ERROR, `无权限提交！`)

  if (!joinInfo) return resultsModel.error(CODE_TYPES.SYSTEM_ERROR, '本局id不存在')

  return {
    joinInfo
  }
}
